package com.fix.util;

import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class HttpCommand {
	private HttpRequest request;
	private MultiThreadedHttpConnectionManager connectionManager;
	private HttpClient client;
	protected FixConfig config = null;
	private static final Log LOGGER = LogFactory.getLog(HttpCommand.class);

	public HttpCommand(HttpRequest request) {
		this.request = request;

		try {
			config = new FixConfig();
		} catch (Exception e) {
			LOGGER.error("", e);
		}
		connectionManager = new MultiThreadedHttpConnectionManager();
		client = new HttpClient(connectionManager);
		client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
				Integer.valueOf(config.getConnectionTimeOut()));
		client.getParams().setParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT,
				Integer.valueOf(config.getConnectionTimeOut()));
	}

	public void postData() throws IOException {
		String parameters = null;
		String output = null;
		parameters = request.getUrlParameters();
		StringBuffer urlBuffer = new StringBuffer(request.getUrl());
		GetMethod method = new GetMethod(urlBuffer.toString());		
		method.setQueryString(parameters);
		System.out.println(parameters);
		
		try {
			int returnCode = client.executeMethod(method);
			String outBody = method.getResponseBodyAsString();

			output = outBody;
		} catch (Exception e) {
			output = e.getMessage();
		} finally {
			method.releaseConnection();
		}

		request.setResponse(output);
	}

	public static String encode(String source) {
		return new String(Base64.encodeBase64(source.getBytes()));
	}

	public HttpRequest getRequest() {
		return request;
	}

	public void setRequest(HttpRequest request) {
		this.request = request;
	}

	public FixConfig getConfig() {
		return config;
	}

	public void setConfig(FixConfig config) {
		this.config = config;
	}
}
